﻿@using Microsoft.Extensions.Hosting;
@using System.Text.Json;
@inherits AdminCompontentBase
@inject IConfigurationApiManage ConfigurationApiManage
@inject IConfigurationApi ConfigurationApi
@inject IHostEnvironment HostEnvironment
@inject IMultiEnvironmentUserContext MultiEnvironmentUserContext

<div class="i18n-configer">
    <STextField Value="Name" ValueChanged="NameChanged" ValueExpression="NameExpression"
                Required
                Label="Key"
                Action="@(props => { props.Content = T("DisplayName"); props.OnClick = _ => OpenConfigDialog(); })"
                Type="text"
                Suffix="@DT(Name)">
    </STextField>
</div>

<MDialog @bind-Value="_dialog" Width="400" Persistent>
    <MCard Class="pa-4">
        <MCardTitle Class="justify-center">
            @($"{Name}{T("DisplayName")}")
        </MCardTitle>
        <MCardText>
            @foreach (var _displayName in _displayNames)
            {
                <STextField Class="my-2" Label="@_displayName.Key" @bind-Value=_displayName.Value />
            }
        </MCardText>
        <MCardActions>
            <SButton Color="primary" Outlined Width="140"
                     OnClick="() => _dialog = false">
                @T("Cancel")
            </SButton>
            <MSpacer></MSpacer>
            <SButton Color="primary" Width="140"
                     OnClick="Save">
                @T("Ok")
            </SButton>
        </MCardActions>
    </MCard>
</MDialog>

@code {
    [Parameter]
    public string Name { get; set; } = string.Empty;

    [Parameter]
    public EventCallback<string> NameChanged { get; set; }

    [Parameter]
    public Expression<Func<string>>? NameExpression { get; set; }

    bool _dialog;
    List<KeyValue<string, string>> _displayNames = new();

    private Task OpenConfigDialog()
    {
        _displayNames = new();
        var publicSection = ConfigurationApi.GetPublic();
        foreach (var culture in I18n.SupportedCultures)
        {
            var cultureName = culture.Name.ToLower();
            var value = publicSection.GetValue<string>($"{DynamicTranslateProvider.I18N_KEY}{cultureName}:{Name}", "");
            _displayNames.Add(new KeyValue<string, string>(cultureName, value ?? string.Empty));
        }
        _dialog = true;
        return Task.CompletedTask;
    }

    private async Task Save()
    {
        var publicSection = ConfigurationApi.GetPublic();
        var environment = MultiEnvironmentUserContext.Environment ?? HostEnvironment.EnvironmentName;
        foreach (var _displayName in _displayNames)
        {
            var itemKey = $"{DynamicTranslateProvider.I18N_KEY}{_displayName.Key}";
            var itemSection = publicSection.GetSection(itemKey);
            if (!itemSection.Exists())
            {
                var data = new Dictionary<string, object> { { Name, _displayName.Value } };
                await ConfigurationApiManage.AddAsync(environment, "Default", "public-$Config", new Dictionary<string, object> { { itemKey, data } });
            }
            else
            {
                var data = itemSection.Get<Dictionary<string, object>>();
                MasaArgumentException.ThrowIfNull(data);
                data[Name] = _displayName.Value;
                await ConfigurationApiManage.UpdateAsync(environment, "Default", "public-$Config", itemKey, data);
            }
        }
        _dialog = false;
    }

    public class KeyValue<TKey, TVal>
    {
        public TKey Key { get; set; }
        public TVal Value { get; set; }

        public KeyValue(TKey key, TVal value)
        {
            this.Key = key;
            this.Value = value;
        }
    }
}
